package org.sunyaxing.transflow.transflowapp.plugins.inputs.gitlabairevire;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.sunyaxing.transflow.transflowapp.plugins.inputs.GitLabHookInputExt;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/api")
public class GitlabHook {

    // 所有已经注册的钩子插件
    private static final Map<String, GitLabHookInputExt> HOOK_CONSUMER = new HashMap<>();
    private static final Logger log = LoggerFactory.getLogger(GitlabHook.class);

    @GetMapping("/aireview")
    public String aireview(@RequestParam("pid") Long projectId, @RequestParam("iid") Long mergeRequestIid) {
        try {
            HOOK_CONSUMER.get("DEF").getDiffFromGitlab(projectId, mergeRequestIid, new AtomicInteger(0));
        } catch (Exception e) {
            log.error("【P[{}] R[{}]】 GITLAB API 调用失败", projectId, mergeRequestIid);
        }
        return "f";
    }

    @PostMapping("/review")
    public ResponseEntity<String> review(@RequestParam(name = "name", required = false) String name, @RequestBody JSONObject mergeRequestEvent) {
        String extName = StrUtil.emptyToDefault(name, "DEF");
        HOOK_CONSUMER.get(extName).putData(mergeRequestEvent);
        return ResponseEntity.ok("ok");
    }

    public static void registerHook(String name, GitLabHookInputExt hook) {
        if (HOOK_CONSUMER.containsKey(name)) {
            throw new RuntimeException("HOOK_CONSUMER 已存在");
        } else {
            HOOK_CONSUMER.put(name, hook);
        }
    }

    public static void unregisterHook(String name) {
        HOOK_CONSUMER.remove(name);
    }
}
